package cn.silver.framework.satoken.model;

import cn.silver.framework.core.utils.DateUtils;
import cn.silver.framework.core.utils.StringUtils;
import cn.silver.framework.mybatis.enums.RoleTypeEnums;
import cn.silver.module.system.models.RoleModel;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Silver Zhou
 */
@Data
@NoArgsConstructor
@Schema(name = "LoginUser", title = "登录信息对象")
public class LoginUser implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;
    @Schema(title = "登录用户主键")
    private String id;

    @Schema(title = "登录用户账号")
    private String code;

    @Schema(title = "登录用户姓名")
    private String name;

    @Schema(title = "登录用户类型")
    private String type;

    @Schema(title = "会话token")
    private String token;
    @Schema(title = "认证方式")
    private String authType;
    @Schema(title = "登录设备")
    private String deviceType;

    @Schema(title = "登录租户")
    private String tenantId;

    @Schema(title = "当前所属组织")
    private String deptId;

    @Schema(title = "当前任职组织名称")
    private String deptName;

    @Schema(title = "登录时间")
    @JsonFormat(timezone = DateUtils.TIME_ZONE, pattern = DateUtils.YYYY_MM_DD_HH_MM_SS)
    private Date loginTime;

    @Schema(title = "会话到期时间")
    private Long expireTime;

    @Schema(title = "登录IP")
    private String ipaddr;

    @Schema(title = "登录客户端")
    private String browser;
    @Schema(title = "客户端操作平台")
    private String os;
    @Schema(title = "当前登录角色")
    private RoleModel role;
    @Schema(title = "用户具有的角色集")
    private Set<String> roleKeys;
    @Schema(title = "用户具有的权限")
    private Set<String> permission;
    @Schema(title = "用户具有的角色集")
    private List<RoleModel> roles;

    public boolean isAdmin() {
        return RoleTypeEnums.SUPER_ROLE.getCode().equalsIgnoreCase(this.role.getType());
    }

    public String getLoginId() {
        if (StringUtils.isBlank(this.deviceType)) {
            throw new IllegalArgumentException("登录的设备类型不能为空");
        }
        if (StringUtils.isBlank(this.id)) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        return this.deviceType + ":" + id;
    }

}
